<template>
  <div class="choose-userlist">
    <section v-if="config.model !== 'normal'">
      <el-button class="mar-b-20" type="primary" size="mini" @click="toggle">指定商品</el-button>
      <el-table :data="displayData" v-if="displayData.length>0&&isShow">
        <el-table-column label="商品">
          <template slot-scope="scope">
            <div class="flex-row flex-align-c">
              <img v-if="scope.row.image" width="50" height="50" :src="scope.row.image[0]['file_path']" style="margin-right:10px;" />
              <div class="flex-col" v-if="scope.row.sku">
                <p>
                  <span class="orders-red">￥{{scope.row.sku[0]['goods_price']}}</span>
                </p>
                <p>{{scope.row.goods_name}}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总库存">
          <template slot-scope="scope" v-if="scope.row.sku">
            <span>{{scope.row.stock || scope.row.sku[0]['stock_num']}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <div class="operation-group">
              <el-button class="wlm-text" type="text" @click="chooseGoods(scope.row.goods_id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <!-- @close="output" -->
    <el-dialog custom-class="wlm-form-dialog dialog-table" :visible.sync="dialogTableVisible" @close="clearData" width="50%">
      <div class="wlm-dialog-fixheader">
        <span class="wlm-dialog-inlenr">选择商品</span>
      </div>
      <!-- <el-scrollbar> -->
      <div class="wlm-table-content">
        <div class="wlm-dialog-main">
          <div class="flex-row">
            <el-scrollbar>
              <div class="goods-menu">
                <el-tree :data="menuData" :props="defaultProps" accordion @node-click="handleNodeClick"></el-tree>
              </div>
            </el-scrollbar>
            <el-scrollbar style="width:100%;height: 520px;max-height: 520px;">
              <div class="goods-list-box">
                  <div class="goods-serch">
                  <el-input v-model="tableFormatData.userTable.files.name" placeholder="搜索商品名称"></el-input>
                  <i class="el-icon-search pos-col-center" @click="filesSerch"></i>
                </div>
                 <div style="margin-left:10px;">
                     <el-select v-model="tableFormatData.userTable.files.transport_type" placeholder="请选择" @change="filesSerch" v-if="patSetting.plugin.cgp.open">
                          <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                  <!-- <el-input v-model="tableFormatData.userTable.files.name" placeholder="搜索商品名称"></el-input> -->
                  <!-- <i class="el-icon-search pos-col-center" @click="filesSerch"></i> -->
                </div>
                <div v-if="hasTableData.length >0" class="goods-list-group flex-row flex-warp">
                  <div class="goods-list" v-for="(item, index) in tableFormatData.userTable.tableData" :key="index">
                    <div class="goods-item flex-row flex-align-c">
                      <div class="img-center" v-if="item.image && item.image[0]" :style="{'background-image':`url(${item.image[0].file_path})`}"></div>
                      <div class="flex-col flex-align-c flex-justify-b scale-grow">
                        <div class="ellipsis">
                          <p style="line-height:1.6">{{item.goods_name}}</p>
                          <p style="line-height:1.2" class="font-12">库存：{{item.stock}}</p>
                        </div>
                        <!-- <p class="ellipsis"><p>{{item.goods_name}}</p><p>{{item.stock}}</p></p> -->
                        <p class="flex-row flex-align-c flex-justify-b flex-grow-1" style="font-size: 16px;">
                          <span class="text-danger" v-if="item.spec_type=='10'">￥{{item.goods_max_price}}</span>
                          <span class="text-danger" v-if="item.spec_type=='20'">￥{{item.sku[0]['goods_price']}}</span>
                          <el-button
                            :disabled="hasDisabled(item)"
                            :class="{'is-active':currentRow.includes(item.goods_id)}"
                            type="primary"
                            round
                            plain
                            size="mini"
                            style="font-size:12px;"
                            @click="chooseGoods(item.goods_id,item)"
                          >{{`${currentRow.includes(item.goods_id)?'取消':'选择'}`}}</el-button>
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="no-tabledata" v-if="isTableFormatGetEnd && !(hasTableData.length >0)" v-cloak>
                  <svg-icon style icon-class="notabledata" />
                  <span style="display: block;margin: -45px auto 0;">暂无商品数据</span>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
      <!-- </el-scrollbar> -->
      <div class="pagination-content flex-row flex-justify-b flex-align-c">
        <el-row class="pagination-btns"></el-row>
        <el-pagination
          style="margin-top:20px;margin-bottom:20px;margin-right: 25px;"
          :disabled="!hasTableData"
          @size-change="listPageChange"
          @current-change="listPageChange"
          :current-page.sync="tableFormatData.userTable.pagination.page"
          :page-sizes="tableFormatData.userTable.pagination.pagesizes"
          :page-size.sync="tableFormatData.userTable.pagination.list_rows"
          layout="total, sizes, prev, pager, next, jumper"
          :total="hasTableData.length > 0 ? tableFormatData.userTable.pagination.total : 0"
        ></el-pagination>
      </div>
      <div class="wlm-dialog-fixfooter">
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="toggle">取 消</el-button>
          <el-button size="small" type="primary" @click="saveChoose">确 定</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  goodsclassIndex,
  goodsCommon,
  addCommon,
  goodsIndex,
  categoryIndex
} from '@/api/merchandise'
import mixins from '@/mixins/mixins'
import defaultConfig from './utils/config'
import {
  tooggleArray
} from '@/utils/index'
import power from '@/mixins/power'
export default {
  mixins: [defaultConfig.mixins, mixins.getters('Table'),power],
  props: {
    defaultConfig: {
      type: Object,
      default: () => {
        return defaultConfig
      }
    },
    isShow: {
      type: Boolean,
      default: true
    },
    comUrl: {
      type: String,
      default: ''
    },
    gift:{
       type: String,
       default: ''
    },
    ismeal:{
       type: String,
       default: ''
    }
  },
  watch: {
    'config.initList': {
      handler(newData, oldData) {
        if (Array.isArray(newData) && newData.length > 0) {
          this.$nextTick(() => {
            newData.map((item) => {
              const { goods_id, goods = [] } = item
              if (goods_id) {
                this.currentRow.push(goods_id)
              }

              if (Array.isArray(goods) && goods.length > 0) {
                this.displayData = [...this.displayData, ...goods]
              } else {
                this.displayData.push(item)
              }
            })
          })
          console.log(this.displayData, 'config.initList')
        }
      },
      immediate: true,
      deep: false
    },
    // 'config.item':{
    //   handler(newData,oldData){
    //     console.log("newData55555555555",newData)
    //   }
    // },
    // 'config.params': {
    //   handler(newData, oldData) {
    //     console.log(this.config.params, 'config')
    //     // console.log(newData, oldData, 'ojbkk')
    //     if (newData && typeof newData === 'object') {
    //       this.$nextTick(() => {
    //         this.tableFormatData.userTable.files = { ...this.tableFormatData.userTable.files, ...this.config.params }
    //       })
    //     }
    //   },
    //   immediate: true,
    //   deep: true
    // }
    displayData(newData, oldData) {
      console.log('displayData', this.newData)
    }
  },
  data() {
    return {
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      newis_meal:1,
      options:[
        {value: '',label: '全部'},
        {value: '40',label: '社区商品'},
        {value: '-1',label: '普通商品'},
        ],
      displayData: [],
      menuData: [],
      currentRow: [],
      closable: true,
      dialogTableVisible: false,
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList:  this.comUrl === 'seckillList' ? goodsCommon : goodsIndex
          },
          tableData: [],
          files: this.comUrl === 'seckillList' ? {
                                                name: '',
                                                sale_type: '1',
                                                category_id: '',
                                                ids: [],
                                                checkall: '0',
                                                transport_type:''
                                              }:this.gift=='gift'?{
                                                name: '',
                                                ids: [],
                                                checkall: '0',
                                                category_id: '',
                                                transport_type:50,
                                              }:this.ismeal =='ismeal'?{
                                                name: '',
                                                ids: [],
                                                checkall: '0',
                                                category_id: '',
                                                transport_type:'',
                                                is_meal:1,
                                              }:{
                                                name: '',
                                                ids: [],
                                                checkall: '0',
                                                category_id: '',
                                                transport_type:'',
                                              },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0
          }
        }
      }
    }
  },
  computed: {
    hasDisabled(item) {
      return (item) => {
        let hasDisabled = false
        const disabled = this.config.disabled
        // is_reservation  是否开启预约
        // transport_type:  物流方式 10不需要物流 20 需要物流 30电子卡密 40社区团购 50礼包商品
        // goods_min_price   最低价
        // spec_type    商品规格(10单规格 20多规格 30多套餐)
        // is_meal    礼包商品 1是 2否
        // member_exclusive  是否是会员商品 1是 2否
        // goods_status 10上架  20下架  30自定义上架时间

        // console.log('this.config+++++++++++', this.config)
        // console.log('disabled+++++++++++', disabled)
        //  console.log('item+++++++++++', item)

        if (Array.isArray(disabled) && disabled.length > 0) {
          disabled.map(lableItem => {
            let hasValue;
            if(this.comUrl === 'seckillList'){
              hasValue = item[`${lableItem.label}`] === lableItem.value ? true : false
            }
            else{
              hasValue = lableItem.reverse ? item[`${lableItem.label}`] !== lableItem.value : item[`${lableItem.label}`] === lableItem.value
            }
            if (hasValue) {
              hasDisabled = true
            }
            if (this.config.keys == 'keyrow' && item.is_reservation == 1) { // 在会员卡页面传keys === 'keyrow'标识，并且开启预约时，禁用选择按钮
              hasDisabled = true
            }
            if(this.config.thumbtn == 'thumbtns' && item.transport_type == 40 ){//在点赞页面传thumbtn == 'thumbtns'标识，团购商品不能添加
                 hasDisabled = true
            }
            if (this.config.seckill == 'seckills' && ( (this.comUrl === 'seckillList' && item.partake_in == 1 ) || item.is_meal == 1 || item.transport_type == 30 || item.transport_type == 50 || item.goods_min_price == 0 || item.is_step_price ==1)) { // 在秒杀页面传seckill === 'seckills'标识，多套餐不能放到秒杀,或者卡密商品不能放秒杀，礼包商品不能放秒杀，禁用选择按钮
              hasDisabled = true
            }
            if (this.config.collage == 'collages' && (item.is_meal == 1 || item.transport_type == 30 || item.transport_type == 50 || item.goods_min_price == 0 || item.is_step_price ==1)) { // 在拼团页面传collage=='collages'标识，多套餐不能放到拼团，禁用选择按钮
              hasDisabled = true
            }
            if (this.config.bargain == 'bargain' && (item.spec_type == 20 || item.is_reservation == 1 || item.transport_type == 30 || item.transport_type == 50 || item.goods_min_price == 0 || item.is_step_price ==1)) { // 在砍价页面传bargain==bargain标识，并且开启预约时，或者是多规格，禁用选择按钮
              hasDisabled = true
            }
            //卡密串码关联商品时，不能选择卡密商品（自己添加的，如果没有，就会出问题）和礼包商品（礼包商品有多个核销码）
            if (this.config.concatenation == 'concatenation' && (item.transport_type == 50 || item.transport_type == 30)) {
              hasDisabled = true
            }
            // if (this.config.thenment=='thenments'&&(item.spec_type == 10)) {
            //   hasDisabled = true
            // }
            // if(this.config.statusgood=='statusgoods' && item.goods_status==20){
            //    hasDisabled = true
            // }
            if (item.goods_status != 10) { // 以下架的商品在搭配商品中不能选择
              hasDisabled = true
            }
            return hasValue
          })
        }
        return hasDisabled
      }
    },

    gitGoodsIds() {
      const goodsIds = []
      this.displayData.map(item => {
        goodsIds.push(item.goods_id)
      })
      return goodsIds
    }
  },
  created() {
    categoryIndex().then((response) => {
      const {
        data: msgData = {}
      } = response
      this.menuData = [{
        category_id: '',
        name: '全部',
        child: []
      }, ...msgData.data]
      console.log("fdsf20fdsfdsfds范德萨范德萨发",(this.gift=='gift'&&this.ismeal =='ismeal'),this.gift=='gift',this.ismeal =='ismeal')
    })
  },
  methods: {
    toggle() {
      this.dialogTableVisible = !this.dialogTableVisible
    },
    saveChoose() {
      const _this = this
      if (_this.comUrl === 'seckill') {
        addCommon({
          sale_type: [1],
          goods_id: _this.gitGoodsIds
        }).then(response => {
          const {
            data: {
              code,
              msg
            }
          } = response
          if (code === 1) {
            _this.output()
            _this.$message.success(msg)
          } else {
            _this.$message.error(msg)
          }
        })
        _this.toggle()
      }
      else{
        this.toggle()
        this.output()
      }
    },
    handleNodeClick(data) {
      this.tableFormatData.userTable.files.category_id = data.category_id
      this.filesSerch()
    },
    chooseGoods(ids, item) {
      console.log('item+++++++++++++++', item)
      console.log('00000000000000000000', this.config)
      const isUnique = this.config.unique
      if (!isUnique) {
        this.currentRow = tooggleArray(this.currentRow, ids)
      } else {
        this.currentRow = [ids]
      }
      if (this.currentRow.includes(ids)) {
        const { sku, spec_type } = item
        const filterCustorm = this.filterCustormParams(item)
        let $sku = sku
        if (spec_type === 10 && Array.isArray(sku)) {
          $sku = [sku[0]]
        }
        filterCustorm.sku = $sku
        filterCustorm.common_id = item.common_id
        // console.log('itemitemitemitemitemitem',item)
        // filterCustorm.first_grade = item.first_grade || 0
        console.log(filterCustorm, 'filterCustorm=>filterCustorm')
        this.displayData.push(filterCustorm)
      } else {
        const newIndex = this.displayData.findIndex((displayItem) => {
          return displayItem.goods_id === ids
        })
        console.log("......................",this.displayData)
        this.displayData = [...this.displayData]
        console.log("fsdfdsfdfgghhhhhhhhhhhhhhhhhhhhhhhhh",newIndex)
        this.displayData.splice(newIndex, 1)
      }
    },
    clearData() {
      // console.log("xxxxxxxx",'clearData')
      if (this.config.model !== 'display') {
        console.log(this.config.model, 'clearData')
        this.currentRow = []
        this.displayData = []
      }
    },
    output() {
      if (Object.prototype.toString.call(this.changeEvt) === '[object Function]') {
        // console.log('//////////////////////////',this.displayData)
        this.changeEvt({ currentRow: this.currentRow, displayData: this.displayData, key: 'ChooseGoods' }, this.updateConfig.bindKey)
      }
      // this.displayData = this.currentRow
      // console.log('displayData', this.displayData)
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-userlist {
  font-size: 14px;
  margin-bottom: 10px;

  /deep/ .pagination-content .el-input {
    width: 100px;
  }

  .tag-list .el-tag {
    width: auto;
    white-space: nowrap;
    text-overflow: ellipsis;

    & + .el-tag {
      margin-left: 5px;
    }
  }

  .wlm-dialog-main {
    max-height: 520px;
  }

  /deep/ .is-horizontal {
    display: none;
  }

  /deep/ .el-scrollbar__view {
    font-size: 16px;
  }

  .goods-menu {
    width: 200px;
    max-height: 520px;
    padding-bottom: 12px;
    overflow-x: hidden;

    /deep/ .el-tree-node__content {
      .el-tree-node__expand-icon:not(.is-leaf) {
        color: #409eff !important;
      }

      &:hover {
        color: #fff;
        background: #409eff !important;

        .el-tree-node__expand-icon:not(.is-leaf) {
          color: #fff !important;
        }
      }
    }

    /deep/ .el-tree-node:focus > .el-tree-node__content {
      color: #fff;
      background: #409eff !important;

      .el-tree-node__expand-icon:not(.is-leaf) {
        color: #fff !important;
      }
    }

    /deep/ .el-tree-node.is-current:not(.is-expanded) {
      color: #fff;
      background: #409eff !important;

      .el-tree-node__expand-icon:not(.is-leaf) {
        color: #fff !important;
      }
    }

    /deep/ .el-tree-node.is-current.is-expanded > .el-tree-node__content {
      color: #fff;
      background: #409eff !important;

      .el-tree-node__expand-icon:not(.is-leaf) {
        color: #fff !important;
      }
    }
  }

  .goods-list-box {
    width: 100%;
    min-height: 520px;
    padding: 20px 20px;
    margin-top: -20px;
    border-left: 1px solid #f2f2f2;

    .no-tabledata {
      text-align: center;

      svg {
        font-size: 20em;
      }
    }

    /deep/ .goods-serch {
      position: relative;
      margin-bottom: 20px;
      text-align: left;

      .el-input__inner {
        width: 200px;
        border: none;
        background: rgb(237, 237, 237);
        border-radius: 20px;
        font-size: 12px;
      }

      i {
        cursor: pointer;
        left: 200px;
        margin-left: -35px;
        font-size: 20px;
      }
    }

    .goods-list {
      width: 50%;

      &:not(:nth-last-child(1)) {
        padding-bottom: 20px;
      }

      .goods-item {
        border: 1px solid #d8d1d1;
        margin-right: 20px;
        padding: 8px 10px;
        border-radius: 3px;

        .img-center {
          border-radius: 10px;
          width: 90px;
          height: 80px;
        }

        .scale-grow {
          padding: 0 5px;
        }

        .ellipsis {
          width: 100%;
          font-size: 13px;
          text-align: left;
          margin-bottom: 16px;

          & + p.flex-row {
            width: 100%;
          }
        }

        .text-danger + .el-button {
          width: 62px;
          background: transparent;

          &:not(.is-not) {
            color: #409eff;
          }

          &.is-not {
            border-color: transparent;
            color: #fff !important;
            background: rgb(203, 203, 203) !important;
          }

          &.is-active {
            border-color: transparent;
            color: #fff !important;
            background: #409eff !important;
          }

          &.is-disabled {
            border-color: transparent;
            color: #fff !important;
            background: #c0c4cc !important;
          }
        }
      }
    }
  }
}
</style>
